<?php
namespace faceid;
/**
 * @Author: 小尤
 * @Date:   2017-08-30
 * @note:   公众号发红包,企业付款类
 * @from:   CSDN博客(江南极客:http://blog.csdn.net/sinat_35861727?viewmode=contents)
 */

class Faceid{

    /**
     * 默认支付参数配置
     * @var array
     */
    private $config = array(
        'apiKey'		=> 'xU8mAR2tDT8PxBbBzgnKPoVvu9YVo10T',
        'appSecret'	 	=> 'Drqv6v43f1EM0Qubj3Bg8uv-X5Gln7wn',
        'liveness_type' => 'meglive',
        'comparison_type'=> '1'
    );

    public function __construct($config = array()){
        $this->config   =   array_merge($this->config,$config);
    }

    /**
     * 使用 $this->name=$value 	配置参数
     * @param  string $name 	配置名称
     * @param  string $value    配置值
     */
    public function __set($name,$value){
        if(isset($this->config[$name])) {
            $this->config[$name] = $value;
        }
    }

    /**
     * 使用 $this->name 获取配置
     * @param  string $name 配置名称
     * @return multitype    配置值
     */
    public function __get($name) {
        return $this->config[$name];
    }

    public function __isset($name){
        return isset($this->config[$name]);
    }

    //----------------------------------------------------------重点看这里---------------------------------------------------------

    /**
     * 获取biz_token
     * @param string $idcard_name 	身份证姓名
     * @param string $idcard_number 	身份证号码
     */
    public function get_biz_token($idcard_name,$idcard_number){
        $config = $this->config;

        $data = array(
            'sign' 		=> self::gen_sign($config['apiKey'],$config['appSecret'],100000),
            'sign_version'     	=> 'hmac_sha1',
            'liveness_type' 			=> $config['liveness_type'],
            'comparison_type' 			=> $config['comparison_type'],
            'idcard_name' 		=> $idcard_name,
            'idcard_number'    		=> $idcard_number
        );



        $url = 'https://api.megvii.com/faceid/v3/sdk/get_biz_token';
        //发送post请求
        $res = self::curl_post($url, $data);

        return $res;
    }


    /**
     * 身份证识别
     * @param string $idcard_name 	身份证姓名
     * @param string $idcard_number 	身份证号码
     */
    public function ocridcard($idcard_img){
        $config = $this->config;

        $data = array(
            'api_key' 		=> $config['apiKey'],
            'api_secret'     	=> $config['appSecret'],
            'image' 			=> $idcard_img
        );



        $url = 'https://api.megvii.com/faceid/v3/ocridcard';
        //发送post请求
        $res = self::curl_post($url, $data);

        return $res;
    }


    //-------------------------------------------------------------------------------------------------------------------------------

    /**
     * 将一个数组转换为 XML 结构的字符串
     * @param array $arr 要转换的数组
     * @param int $level 节点层级, 1 为 Root.
     * @return string XML 结构的字符串
     */
    protected function array2xml($arr, $level = 1) {
        $s = $level == 1 ? "<xml>" : '';
        foreach($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value['TagName']);
            }
            if(!is_array($value)) {
                $s .= "<{$tagname}>".(!is_numeric($value) ? '<![CDATA[' : '').$value.(!is_numeric($value) ? ']]>' : '')."</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
        return $level == 1 ? $s."</xml>" : $s;
    }


    /**
     * 将xml转为array
     * @param  string 	$xml xml字符串
     * @return array    转换得到的数组
     */
    protected function xml2array($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }

    /**
     *
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return 产生的随机字符串
     */
    protected function getNonceStr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }


    /**
     * 获取IP地址
     * @return [String] [ip地址]
     */
    protected function getip() {
        static $ip = '';
        $ip = $_SERVER['REMOTE_ADDR'];
        if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
            $ip = $_SERVER['HTTP_CDN_SRC_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] AS $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }

    /**
     * 微信支付发起请求
     */
    protected function curl_post($url, $data, $second=30){

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => $second,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            return $response;
        }
    }

    public function RAS(){
        $config = $this->config;
        $data = [
            'mch_id'    => $config['mch_id'],
            'nonce_str' => self::getNonceStr(),
            'sign_type' => 'MD5'
        ];
        $data['sign'] = self::makeSign($data);

        $xmldata = self::array2xml($data);

        $url = 'https://fraud.mch.weixin.qq.com/risk/getpublickey';
        //将数据发送到接口地址
        $res = self::curl_post_ssl($url, $xmldata);
        if(!$res){
            return array('status'=>0, 'msg'=>"Can't connect the server" );
        }

        // 这句file_put_contents是用来查看服务器返回的结果 测试完可以删除了
        //file_put_contents('./log.txt',$res,FILE_APPEND);

        $content = self::xml2array($res);

        if(strval($content['return_code']) == 'FAIL'){
            return array('status'=>0, 'msg'=>strval($content['return_msg']));
        }
        if(strval($content['result_code']) == 'FAIL'){
            return array('status'=>0, 'msg'=>strval($content['err_code']).':'.strval($content['err_code_des']));
        }


        if(strval($content['result_code'])== 'SUCCESS'){
            if(!file_exists("publicert")) {
                mkdir("publicert");
            }
            $a="cer/publicrsa.pem";
            $fp=fopen($a,"w+");
            fwrite($fp,$content['pub_key']);
            fclose($fp);

        }
        return $content;

    }

    public function rsa_encrypt($str)
    {
        $pu_key = openssl_pkey_get_public(file_get_contents('cer/publicrsa.pem'));  //读取公钥内容
        $encryptedBlock = '';
        $encrypted = '';
// 用标准的RSA加密库对敏感信息进行加密，选择RSA_PKCS1_OAEP_PADDING填充模式
        //   （eg：Java的填充方式要选 " RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING"）
// 得到进行rsa加密并转base64之后的密文
        openssl_public_encrypt($str,$encryptedBlock,$pu_key,OPENSSL_PKCS1_OAEP_PADDING);
        $str_base64  = base64_encode($encrypted.$encryptedBlock);
        return $str_base64;
    }

    public function gen_sign($apiKey, $apiSecret, $expired){
        $rdm = rand();
        $current_time = time();
        $expired_time = $current_time + $expired;
        $srcStr = "a=%s&b=%d&c=%d&d=%d";
        $srcStr = sprintf($srcStr, $apiKey, $expired_time, $current_time, $rdm);
        $sign = base64_encode(hash_hmac('SHA1', $srcStr, $apiSecret, true).$srcStr);
        return $sign;
    }


}





